﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;

namespace Jiuyong
{
	/// <summary>
	/// 程序单实例启动，重复启动激活已有实例窗口的实现。
	/// </summary>
    public static class OneInstance
    {
        static Semaphore semaphore;//= new Semaphore(1, 1, "OneInstance");
		static Thread threadBackground;
        static OneInstance()
        {
			semaphore = new Semaphore(1, 1, "OneInstance", out _isFirstInstance);
			threadBackground = new Thread(new ThreadStart(Work));
			threadBackground.IsBackground = true;
        }

		private static bool _isFirstInstance;
		/// <summary>
		/// 判断程序是否为首个实例。
		/// </summary>
		public static bool IsFirstInstance
		{
			get
			{
				return _isFirstInstance;
			}
		}

		/// <summary>
		/// 激活已存在的实例。
		/// </summary>
        public static void ActivateInstance()
        {
            try
            {
                semaphore.Release();
            }
            catch (SemaphoreFullException)
            { 
            }
        }

		private static Form _defaultForm;
		//public static Form MainForm
		//{
		//    get
		//    {
		//        return _defaultForm;
		//    }

		//    set
		//    {
		//        _defaultForm = value;
		//    }
		//}

		//delegate void BackCall();
		static void ShowBack()
		{
			_defaultForm.Show();
			_defaultForm.Activate();
			//_defaultForm.TopMost = true;
			//_defaultForm.TopMost = false;
		}

		/// <summary>
		/// 设置实例的默认窗口，以便在重复启动实例时激活。
		/// </summary>
		/// <param name="defaultForm">程序默认的激活窗口。</param>
        public static void StartDefaultWindow(Form defaultForm)
        {
			_defaultForm = defaultForm;
			threadBackground.Start();
        }

		static void Work()
		{
			while (true)
			{
				semaphore.WaitOne();
				_defaultForm.Invoke(new ThreadStart(ShowBack));
			}
		}

    }
}
